#include "../Server/Source/server.hpp"

// void Useage(char* ch[])
// {
//     std::cout << "Useage: " << ch[0] << " port" << std::endl;
// }

// int main(int argc,char* argv[])
// {
//     if(argc != 2)
//     {
//         Useage(argv);
//         exit(1);
//     }

//     Socket _listensockfd;
//     _listensockfd.CreateServer(std::stoi(argv[1]));
//     while(1)
//     {
//         int _sockfd = _listensockfd.Accept();
//         Socket _Osockfd(_sockfd);
//         char buffer[1024] = {0};
//         _Osockfd.Recv(buffer,sizeof(buffer)-1);
//         std::cout << "Client say: " << buffer << std::endl;
//         _Osockfd.Send(buffer,sizeof(buffer)-1);

//         _Osockfd.Close();

//     }
//     _listensockfd.Close();

//     return 0;

// }

char buffer[1024] = {0};



void Recv(int fd, Channel *_channel)
{
    int n = recv(fd, buffer, sizeof(buffer) - 1, 0);

    std::cout << buffer << std::endl;
    _channel->EnableWrite();
}

void Send(int _fd, Channel *_channel)
{
    int n = send(_fd, buffer, sizeof(buffer) - 1, 0);
    _channel->DisableWrite();
}

void Accept(int _listfd, EventLoop *_poller)
{
        int _sockfd = accept(_listfd, nullptr, nullptr);
        Channel *_channel = new Channel(_sockfd, _poller);
        _channel->SetReadAction(std::bind(Recv, _channel->Fd(), _channel));
        _channel->SetWriteAction(std::bind(Send, _channel->Fd(), _channel));
        _channel->EnableRead();
}

int main()
{
    EventLoop _loop;
    Socket _listsockfd;
    _listsockfd.CreateServer(8084);
    Channel _listenChannel(_listsockfd.GetFd(), &_loop);


    _listenChannel.SetReadAction(std::bind(Accept, _listsockfd.GetFd(), &_loop));
    _listenChannel.EnableRead();

    std::vector<Channel *> _active;
    while (1)
    {
        _loop.Start();
    }
}